/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.log.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import org.springblade.common.enums.IntegralType;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.log.entity.IntegralLogEntity;
import org.springblade.modules.log.excel.IntegralTrainingLogImporter;
import org.springblade.modules.log.service.IIntegralLogService;
import org.springblade.modules.log.service.IIntegralTrainingService;
import org.springblade.modules.log.service.IIntegralYearLogService;
import org.springblade.modules.personal.entity.UserBaseEntity;
import org.springblade.modules.personal.service.IUserBaseService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.log.entity.IntegralTrainingLogEntity;
import org.springblade.modules.log.vo.IntegralTrainingLogVO;
import org.springblade.modules.log.excel.IntegralTrainingLogExcel;
import org.springblade.modules.log.wrapper.IntegralTrainingLogWrapper;
import org.springblade.modules.log.service.IIntegralTrainingLogService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
 * 教师培训记录台账 控制器
 *
 * @author junxin
 * @since 2023-05-18
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-integralTrainingLog/integralTrainingLog")
@Api(value = "培训记录台账明细", tags = "培训记录台账明细接口")
public class IntegralTrainingLogController extends BladeController {

	private final IIntegralTrainingLogService integralTrainingLogService;
	private final IIntegralTrainingService integralTrainingService;
	private final IIntegralLogService integralLogService;
	private final IUserBaseService userBaseService;

	/**
	 * 教师培训记录台账 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入integralTrainingLog")
	public R<IntegralTrainingLogVO> detail(IntegralTrainingLogEntity integralTrainingLog) {
		IntegralTrainingLogEntity detail = integralTrainingLogService.getOne(Condition.getQueryWrapper(integralTrainingLog));
		return R.data(IntegralTrainingLogWrapper.build().entityVO(detail));
	}

	/**
	 * 教师培训记录台账 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入integralTrainingLog")
	public R<IPage<IntegralTrainingLogVO>> list(@ApiIgnore @RequestParam Map<String, Object> integralTrainingLog, Query query) {
		QueryWrapper<IntegralTrainingLogEntity> queryWrapper = Condition.getQueryWrapper(integralTrainingLog, IntegralTrainingLogEntity.class);

//		queryWrapper.lambda().eq(IntegralTrainingLogEntity::getParentId, 0L);
		BladeUser user = AuthUtil.getUser();
		UserBaseEntity userBaseEntity = userBaseService.selectByUserId(user.getUserId());
		if (Func.isBlank(user.getRoleName()) || !user.getRoleName().contains("taizhang_guanliyuan")) {
			//过滤父子项同时出现的数据
			List<IntegralTrainingLogEntity> manageList = integralTrainingLogService.list(Wrappers.<IntegralTrainingLogEntity>query()
				.lambda().eq(IntegralTrainingLogEntity::getManageUser, userBaseEntity.getUserName()).eq(IntegralTrainingLogEntity::getIsDeleted,0));
			List<Long> parentIdList = manageList.stream().filter(manage -> manage.getParentId() == 0L)
				.map(IntegralTrainingLogEntity::getId).collect(Collectors.toList());
			List<Long> filterIdList = manageList.stream().filter(manage -> parentIdList.contains(manage.getParentId()))
				.map(IntegralTrainingLogEntity::getId).collect(Collectors.toList());
			if (Func.isNotEmpty(filterIdList))queryWrapper.lambda().notIn(IntegralTrainingLogEntity::getId,filterIdList);

			queryWrapper.lambda().eq(IntegralTrainingLogEntity::getManageUser, userBaseEntity.getUserName());
		}else {//台账管理员只需从主项开始即可
			queryWrapper.lambda().eq(IntegralTrainingLogEntity::getParentId,0L);
		}

		IPage<IntegralTrainingLogEntity> pages = integralTrainingLogService.page(Condition.getPage(query), queryWrapper);
		IPage<IntegralTrainingLogVO> integralTrainingLogVOIPage = IntegralTrainingLogWrapper.build().pageVO(pages);

		integralTrainingLogVOIPage.getRecords().forEach(integralTrainingLogVO -> {
			if (Func.isNotEmpty(integralTrainingLogVO.getParentId())
				&& integralTrainingLogVO.getParentId().equals(0L)) {

				LambdaQueryWrapper<IntegralTrainingLogEntity> sonQueryWrapper=new LambdaQueryWrapper<>();
				sonQueryWrapper.eq(IntegralTrainingLogEntity::getParentId, integralTrainingLogVO.getId());

				if (Func.isBlank(user.getRoleName()) || !user.getRoleName().contains("taizhang_guanliyuan")) {
					sonQueryWrapper.eq(IntegralTrainingLogEntity::getManageUser, userBaseEntity.getUserName());
				}

				integralTrainingLogVO.setChildrenList(integralTrainingLogService.list(sonQueryWrapper));
			}
		});
		return R.data(integralTrainingLogVOIPage);
	}

	/**
	 * 教师培训记录台账 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入integralTrainingLog")
	public R save(@Valid @RequestBody IntegralTrainingLogEntity integralTrainingLog) {
		if (Func.isNotEmpty(integralTrainingLog.getManageUser())) {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserName(integralTrainingLog.getManageUser());
			if (Func.isEmpty(userBaseEntity))
				throw new ServiceException("未找到此人:" + integralTrainingLog.getManageUser());
		}
		//非台账管理员新增台账，则默认指派人为新增者
		BladeUser user = AuthUtil.getUser();
		if (Func.isBlank(user.getRoleName()) || !user.getRoleName().contains("taizhang_guanliyuan")) {
			integralTrainingLog.setManageUser(user.getUserName());
		}
		return R.status(integralTrainingLogService.save(integralTrainingLog));
	}

	/**
	 * 教师培训记录台账 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入integralTrainingLog")
	public R update(@Valid @RequestBody IntegralTrainingLogEntity integralTrainingLog) {
		if (Func.isNotEmpty(integralTrainingLog.getManageUser())) {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserName(integralTrainingLog.getManageUser());
			if (Func.isEmpty(userBaseEntity))
				throw new ServiceException("未找到此人:" + integralTrainingLog.getManageUser());
		}
		return R.status(integralTrainingLogService.updateById(integralTrainingLog));
	}

	/**
	 * 教师培训记录台账 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(integralTrainingLogService.deleteLogic(Func.toLongList(ids)));
	}


	@GetMapping("/assign")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "台账指派", notes = "传入integralTrainingLog")
	public R assignTraining(@ApiParam(value = "用户姓名", required = true) @RequestParam String userName
		, @ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		UserBaseEntity userBaseEntity = userBaseService.selectByUserName(userName);
		if (Func.isEmpty(userBaseEntity)) throw new ServiceException("未找到此人:" + userName);

		LambdaUpdateWrapper<IntegralTrainingLogEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(IntegralTrainingLogEntity::getId, idList);
		updateWrapper.set(IntegralTrainingLogEntity::getManageUser, userName);
		return R.status(integralTrainingLogService.update(updateWrapper));
	}

	/**
	 * @param id
	 * @param integralType 学员=3 ，教员=4
	 * @return
	 */
	@GetMapping("/integral-period-user-list")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "赋分用户列表", notes = "传入integralTrainingLog")
	@Transactional(rollbackFor = Exception.class)
	public R integralPeriodUserList(@ApiParam(value = "主键", required = true) @RequestParam String id,
									@ApiParam(value = "积分类型", required = true) @RequestParam Integer integralType) {
		List<IntegralLogEntity> integralLogList = integralLogService.list(Wrappers.<IntegralLogEntity>query().lambda()
			.eq(IntegralLogEntity::getIntegralResourcesId, id)
			.eq(IntegralLogEntity::getIntegralType, integralType)
			.eq(IntegralLogEntity::getIsDeleted, 0));
		String userNameList = integralLogList.stream().map(IntegralLogEntity::getUserName).collect(Collectors.joining(","));
		String integralsList = integralLogList.stream().map(integral -> String.valueOf(integral.getIntegral())).collect(Collectors.joining(","));
		String periodsList = integralLogList.stream().map(integral -> String.valueOf(integral.getPeriod())).collect(Collectors.joining(","));
		Map<String, String> result = new HashMap<>();
		result.put("userNameList", userNameList);
		result.put("integralsList", integralsList);
		result.put("periodsList", periodsList);
		return R.data(result);
	}


	@GetMapping("/add-student-integral-period")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "学员赋分", notes = "传入integralTrainingLog")
	@Transactional(rollbackFor = Exception.class)
	public R studentIntegralPeriod(
		@ApiParam(value = "台账主键", required = true) @RequestParam String id
		, @ApiParam(value = "姓名集合", required = true) @RequestParam String userName
		, @ApiParam(value = "学时集合", required = true) @RequestParam String periods
		, @ApiParam(value = "积分集合", required = true) @RequestParam String integrals) {
		userIntegralPeriod(id, userName, periods, integrals, IntegralType.TRAINING.getCode());
		return R.success("操作成功");
	}

	@GetMapping("/add-teacher-integral-period")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "教员赋分", notes = "传入integralTrainingLog")
	@Transactional(rollbackFor = Exception.class)
	public R teacherIntegralPeriod(
		@ApiParam(value = "台账主键", required = true) @RequestParam String id
		, @ApiParam(value = "姓名集合", required = true) @RequestParam String userName
		, @ApiParam(value = "学时集合", required = true) @RequestParam String periods
		, @ApiParam(value = "积分集合", required = true) @RequestParam String integrals) {
		userIntegralPeriod(id, userName, periods, integrals, IntegralType.TRAINING_TEACHER.getCode());
		return R.success("操作成功");
	}

	/**
	 * 用户赋分操作
	 * integralType 学员=3 教员4
	 */
	@Transactional(rollbackFor = Exception.class)
	public void userIntegralPeriod(
		String id, String userName, String periods, String integrals, Integer integralType) {
		List<String> periodList = Func.toStrList(periods);
		List<String> integralList = Func.toStrList(integrals);
		List<String> nameList = Func.toStrList(userName);

		if (Func.isNotEmpty(periodList) && periodList.size() != 1 && periodList.size() != nameList.size())
			throw new ServiceException("学时和姓名数量不一致!" +
				"学时数量:" + periodList.size() + ",人员数量:" + nameList.size());

		if (Func.isNotEmpty(integralList) && integralList.size() != 1 && integralList.size() != nameList.size())
			throw new ServiceException("积分数量和姓名数量不一致!"
				+ "积分数量:" + integralList.size() + ",人员数量:" + nameList.size());

		IntegralTrainingLogEntity integralTrainingLogEntity = integralTrainingLogService.getById(id);
		if (Func.isEmpty(integralTrainingLogEntity)) throw new ServiceException("未找到此台账!");
		if (Func.isEmpty(integralTrainingLogEntity.getTrainingMessage()))
			throw new ServiceException("还未实际开展,请开展完成后再进行此操作!");
		if (Func.isEmpty(integralTrainingLogEntity.getStudentIntegral()))
			throw new ServiceException("请先补充台账的学员积分!");
		if (Func.isEmpty(integralTrainingLogEntity.getTeacherIntegral()))
			throw new ServiceException("请先补充台账的教员积分!");
		if (Func.isEmpty(integralTrainingLogEntity.getTrainingHour()))
			throw new ServiceException("请先补充台账的学时!");
		String totalIntegral ="0";
		if (integralType==3) totalIntegral= integralTrainingLogEntity.getStudentIntegral();
		if (integralType==4) totalIntegral= integralTrainingLogEntity.getTeacherIntegral();
		//查出原来的积分项记录
		List<IntegralLogEntity> oldIntegralList = integralLogService.list(Wrappers.<IntegralLogEntity>query().lambda()
			.eq(IntegralLogEntity::getYear, integralTrainingLogEntity.getYear())
			.eq(IntegralLogEntity::getIntegralOrigin, integralTrainingLogEntity.getTrainingType())
			.eq(IntegralLogEntity::getProjectOrigin, integralTrainingLogEntity.getTrainingMessage())
			.eq(IntegralLogEntity::getIntegralType, integralType));

		//删除原本的学员赋分
		for (IntegralLogEntity oldIntegral : oldIntegralList) {
			integralLogService.deleteIntegral(oldIntegral.getId());
		}

		//人员赋分
		for (int i = 0; i < nameList.size(); i++) {
			UserBaseEntity userBaseEntity = userBaseService.selectByUserName(nameList.get(i));
			if (Func.isEmpty(userBaseEntity)) throw new ServiceException("未找到此人:" + nameList.get(i));
			IntegralLogEntity integralLogEntity = new IntegralLogEntity();
			integralLogEntity.setIntegralOrigin(integralTrainingLogEntity.getTrainingType());
			integralLogEntity.setProjectOrigin(integralTrainingLogEntity.getTrainingMessage());
			integralLogEntity.setIntegralType(integralType);
			integralLogEntity.setIntegralGenerateType(2);//系统输入也属于外部导入
			integralLogEntity.setUserId(userBaseEntity.getUserId());
			integralLogEntity.setUserNumber(userBaseEntity.getUserNumber());
			integralLogEntity.setUserName(userBaseEntity.getUserName());
			integralLogEntity.setYear(integralTrainingLogEntity.getYear());
			integralLogEntity.setIntegralTotal(Float.valueOf(totalIntegral));
			integralLogEntity.setRecordDate(DateUtil.formatDate(new Date()));
			integralLogEntity.setIntegralResourcesId(integralTrainingLogEntity.getId());
			//如有多个积分，则是与人一一对应。有且只有一个积分，则是所有人同分
			if (integralList.size() > 1) {
				integralLogEntity.setIntegral(Float.valueOf(integralList.get(i).replace("\"", "")));
			} else {
				integralLogEntity.setIntegral(Float.valueOf(integralList.get(0).replace("\"", "")));
			}

			//如有多个学时，则是与人一一对应。有且只有一个学时，则是所有人学时
			if (periodList.size() > 1) {
				integralLogEntity.setPeriod(Float.valueOf(periodList.get(i).replace("\"", "")));
			} else {
				integralLogEntity.setPeriod(Float.valueOf(periodList.get(0).replace("\"", "")));
			}

			//2.用户添加积分 和添加年度积分和学时
			integralLogService.addIntegralImport(integralLogService.generalIntegralByIntegral(integralLogEntity));
		}
	}


	/**
	 * 导出数据
	 */
	@GetMapping("/export-integralTrainingLog")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导出数据", notes = "传入integralTrainingLog")
	public void exportIntegralTrainingLog(@ApiIgnore @RequestParam Map<String, Object> integralTrainingLog, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<IntegralTrainingLogEntity> queryWrapper = Condition.getQueryWrapper(integralTrainingLog, IntegralTrainingLogEntity.class);
		queryWrapper.lambda().eq(IntegralTrainingLogEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<IntegralTrainingLogExcel> list = integralTrainingLogService.exportIntegralTrainingLog(queryWrapper);
		ExcelUtil.export(response, "教师培训记录台账数据" + DateUtil.time(), "教师培训记录台账数据表", list, IntegralTrainingLogExcel.class);
	}

	/**
	 * 批量导入试题
	 */
	@PostMapping("import-training-integral")
	@ApiOperationSupport(order = 13)
	@ApiOperation(value = "导入教师培训台账记录", notes = "传入excel")
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public R importQuestionBank(MultipartFile file) {
		IntegralTrainingLogImporter integralTrainingLogImporter = new IntegralTrainingLogImporter(integralTrainingLogService, integralTrainingService, integralLogService);
		ExcelUtil.save(file, integralTrainingLogImporter, IntegralTrainingLogExcel.class);
		return R.success("操作成功");
	}

	/**
	 * 导出模板
	 */
	@GetMapping("export-training-integral-template")
	@ApiOperationSupport(order = 14)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<IntegralTrainingLogExcel> list = new ArrayList<>();
		ExcelUtil.export(response, "教师培训台账记录数据模板", "教师培训台账记录数据表", list, IntegralTrainingLogExcel.class);
	}
}
